<template>
  <app-dialog-form
      :title="props.id ? '编辑用户' : '添加用户'"
      :confirm="handleSubmit"
      @closed="handleDialogClosed"
      @open="handleDialogOpen"
  >
    <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
    >
      <el-form-item v-if="props.id" label="唯一属性" prop="openId">
        <el-input disabled v-model="formData.openId" placeholder="请输入唯一属性"/>
      </el-form-item>
      <el-form-item label="用户名称" prop="username">
        <el-input :disabled="props.id>0" v-model="formData.username" placeholder="请输入用户名称"/>
      </el-form-item>
      <el-form-item  label="用户密码" prop="password">
        <el-input v-model="formData.password" placeholder="请输入用户密码"/>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            action=""
            class="avatar-uploader"
            accept='image/png,image/jpg,image/jpeg,image/gif'
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="formData.avatarUrl" :src="formData.avatarUrl" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="formData.nickName" placeholder="请输入联系人姓名"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入手机"/>
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-radio v-model="formData.sex" label="男">男</el-radio>
        <el-radio v-model="formData.sex" label="女">女</el-radio>
        <el-radio v-model="formData.sex" label="">未知</el-radio>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input :rows="2" type="textarea" v-model="formData.description" placeholder="请输入描述"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio v-model="formData.status" label="1">启用</el-radio>
        <el-radio v-model="formData.status" label="0">禁用</el-radio>
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import {ref} from 'vue';
import type {PropType} from 'vue';
import type {IElForm, IFormRule} from '@/types/element-plus';
import {ElMessage} from 'element-plus';
import {IUserInfo} from "@/api/types/user";
import {getUserInfo, saveUserInfo} from "@/api/system";
import type {ElFile} from 'element-plus/es/components/upload/src/upload.type'
import {upload} from "@/api/upload";

const props = defineProps({
  id: {
    type: Number as PropType<number | null>,
    default: null,
  },
});

interface EmitsType {
  (e: 'update:id', value: number | null): void;

  (e: 'success'): void;
}

const emit = defineEmits<EmitsType>();

const form = ref<IElForm | null>(null);
const formLoading = ref(false);
const formData = ref<IUserInfo>({username: ""});

const formRules: IFormRule = {
  username: [{required: true, message: '请输入用户名称', trigger: 'blur'}],
};

const handleDialogOpen = async () => {
  if (props.id) {
    formLoading.value = true;
    formData.value = await getUserInfo(props.id)
    formLoading.value = false;
  }
};


const handleDialogClosed = () => {
  emit('update:id', null);
  formData.value = {username: ""}
  form.value?.clearValidate(); // 清除验证结果
  form.value?.resetFields(); // 清除表单数据
};

const handleSubmit = async () => {
  const valid = await form.value?.validate();
  if (!valid) {
    return;
  }
  await saveUserInfo(formData.value!);
  emit('success');
  ElMessage.success('保存成功');
};


const beforeAvatarUpload = (file: ElFile) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt5M = file.size / 1024 / 1024 < 20

  if (!isJPG) {
    ElMessage.error('Avatar picture must be JPG format!')
  }
  if (!isLt5M) {
    ElMessage.error('Avatar picture size can not exceed 20MB!')
  }
  if (isJPG && isLt5M) {
    upload('image', file).then((data) => {
      formData.value.avatarUrl = data.path
    })
  }
  return false;
}
</script>


<style lang="scss" scoped>
.el-select {
  width: 100%;
}

.el-tree {
  height: 250px;
  overflow: auto;
}

::v-deep(.avatar-uploader .el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  min-height: 140px;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  text-align: center;
  margin-top: 55px;
}

.avatar {
  width: 178px;
  display: block;
}
</style>
